/**
 * 简单的日志工具
 * 生产环境可以替换为Winston或Pino
 */

const LOG_LEVELS = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
};

const currentLevel = LOG_LEVELS[process.env.LOG_LEVEL] || LOG_LEVELS.info;

function formatLog(level, message, meta = {}) {
  const timestamp = new Date().toISOString();
  const logEntry = {
    level,
    timestamp,
    message,
    ...meta,
  };
  
  if (process.env.NODE_ENV === 'development') {
    // 开发环境：彩色输出
    const colors = {
      debug: '\x1b[36m', // cyan
      info: '\x1b[32m',  // green
      warn: '\x1b[33m',  // yellow
      error: '\x1b[31m', // red
    };
    const reset = '\x1b[0m';
    
    console.log(
      `${colors[level]}[${level.toUpperCase()}]${reset} ${timestamp} - ${message}`,
      Object.keys(meta).length > 0 ? meta : ''
    );
  } else {
    // 生产环境：JSON格式
    console.log(JSON.stringify(logEntry));
  }
}

export const logger = {
  debug(message, meta) {
    if (currentLevel <= LOG_LEVELS.debug) {
      formatLog('debug', message, meta);
    }
  },
  
  info(message, meta) {
    if (currentLevel <= LOG_LEVELS.info) {
      formatLog('info', message, meta);
    }
  },
  
  warn(message, meta) {
    if (currentLevel <= LOG_LEVELS.warn) {
      formatLog('warn', message, meta);
    }
  },
  
  error(message, meta) {
    if (currentLevel <= LOG_LEVELS.error) {
      formatLog('error', message, meta);
    }
  },
};

/**
 * 记录审计日志到数据库
 */
export async function logAudit(prisma, data) {
  try {
    await prisma.auditLog.create({
      data: {
        userId: data.userId || null,
        action: data.action,
        resourceType: data.resourceType || null,
        resourceId: data.resourceId || null,
        ipAddress: data.ipAddress || null,
        userAgent: data.userAgent || null,
        status: data.status || 'success',
        details: data.details ? JSON.stringify(data.details) : null,
      },
    });
  } catch (error) {
    logger.error('Failed to log audit', { error: error.message });
  }
}


